/**
 * 需求管理页面JavaScript
 */

// 全局变量
let currentPage = 0;
let pageSize = 10;
let totalPages = 0;
let currentFilters = {};
let selectedRequirements = new Set();
let allProjects = [];
let allDevelopers = [];
let projectsMap = new Map();
let documentCounter = 0;
let tempDocuments = [];

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializePage();
    bindEvents();
    loadInitialData();
});

/**
 * 初始化页面
 */
function initializePage() {
    // 初始化工具提示
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
    
    // 筛选面板已移除
}

/**
 * 绑定事件
 */
function bindEvents() {
    // 全选复选框
    const selectAllEl = document.getElementById('selectAll');
    if (selectAllEl) {
        selectAllEl.addEventListener('change', toggleSelectAll);
    }
    
    // 新建需求相关
    const saveRequirementBtn = document.getElementById('saveRequirementBtn');
    if (saveRequirementBtn) {
        saveRequirementBtn.addEventListener('click', saveRequirement);
    }
    
    const addDocBtn = document.getElementById('addDocBtn');
    if (addDocBtn) {
        addDocBtn.addEventListener('click', addReferenceDocument);
    }
    
    // 模态框事件
    const addRequirementModal = document.getElementById('addRequirementModal');
    if (addRequirementModal) {
        addRequirementModal.addEventListener('show.bs.modal', function() {
            // 只重置表单字段，不清空已添加的文档
            document.getElementById('addRequirementForm').reset();
            document.getElementById('requirementPriority').value = '';
            document.getElementById('requirementOwner').value = '';
            document.getElementById('requirementDeadline').value = '';
            updateProjectOptions();
            updateDeveloperOptions();
        });
        
        // 修复aria-hidden可访问性问题：模态框隐藏时移除焦点
        addRequirementModal.addEventListener('hide.bs.modal', function() {
            // 移除模态框内所有元素的焦点
            const focusedElement = document.activeElement;
            if (focusedElement && addRequirementModal.contains(focusedElement)) {
                focusedElement.blur();
            }
        });
    }
    
    // 全局搜索
    const globalSearch = document.getElementById('globalSearch');
    if (globalSearch) {
        globalSearch.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                performGlobalSearch(this.value);
            }
        });
    }
}

/**
 * 加载初始数据
 */
function loadInitialData() {
    // 先加载项目和开发者数据，再加载需求数据
    Promise.all([
        loadProjectsAsync(),
        loadDevelopersAsync()
    ]).then(() => {
        loadRequirements();
    }).catch(error => {
        console.error('加载初始数据失败:', error);
        // 即使项目数据加载失败，也要加载需求数据
        loadRequirements();
    });
}

// 筛选功能已移除

/**
 * 加载需求列表
 */
function loadRequirements() {
    showLoading();
    
    // 构建查询参数
    const params = new URLSearchParams({
        page: currentPage,
        size: pageSize,
        ...currentFilters
    });
    
    fetch(`/api/requirements?${params}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络请求失败');
            }
            return response.json();
        })
        .then(data => {
            hideLoading();
            // API直接返回数组，不是分页格式
            renderRequirements(data || []);
            
            if (!data || data.length === 0) {
                showEmptyState();
            } else {
                hideEmptyState();
            }
        })
        .catch(error => {
            hideLoading();
            console.error('加载需求列表失败:', error);
            showErrorToast('加载需求列表失败，请重试');
            showEmptyState();
        });
}

/**
 * 渲染需求列表
 */
function renderRequirements(requirements) {
    const tbody = document.getElementById('requirementTableBody');
    tbody.innerHTML = '';
    
    requirements.forEach(requirement => {
        const row = createRequirementRow(requirement);
        tbody.appendChild(row);
    });
    
    // 更新选中状态
    updateSelectAllState();
}

/**
 * 创建需求行
 */
function createRequirementRow(requirement) {
    const row = document.createElement('tr');
    row.dataset.requirementId = requirement.id;
    
    row.innerHTML = `
        <td>
            <input class="form-check-input requirement-checkbox" type="checkbox" 
                   value="${requirement.id}" onchange="toggleRequirementSelection(this)">
        </td>
        <td>
            <a href="/requirements/${requirement.id}" class="requirement-title">
                ${escapeHtml(requirement.title)}
            </a>
            <div class="text-muted small text-truncate-2" style="max-width: 300px;">
                ${escapeHtml(requirement.description || '')}
            </div>
        </td>
        <td>
            <span class="badge bg-secondary" id="project-${requirement.id}">
                ${getProjectDisplayName(requirement.projectId)}
            </span>
        </td>
        <td>
            <span class="priority-badge priority-${requirement.priority?.toLowerCase() || 'medium'}">
                ${getPriorityText(requirement.priority)}
            </span>
        </td>
        <td>
            <span class="text-muted">${requirement.ownerId || '-'}</span>
        </td>
        <td>
            <small class="text-muted">${formatDateTime(requirement.createdAt)}</small>
        </td>
        <td>
            <div class="action-buttons">
                ${createActionButtons(requirement)}
            </div>
        </td>
    `;
    
    return row;
}

/**
 * 创建操作按钮
 */
function createActionButtons(requirement) {
    let buttons = [];
    
    // 查看按钮
    buttons.push(`<a href="/requirements/${requirement.id}" class="btn btn-outline-primary btn-sm" title="查看详情">
        <i class="bi bi-eye"></i>
    </a>`);
    
    // 编辑按钮
    if (requirement.status !== 'CANCELLED') {
        buttons.push(`<button class="btn btn-outline-secondary btn-sm" onclick="editRequirement(${requirement.id})" title="编辑">
            <i class="bi bi-pencil"></i>
        </button>`);
    }
    
    // 激活功能已移除
    
    // 批准和拒绝功能已移除
    
    // 取消按钮
    if (requirement.status !== 'CANCELLED') {
        buttons.push(`<button class="btn btn-outline-danger btn-sm" onclick="cancelRequirement(${requirement.id})" title="取消">
            <i class="bi bi-trash"></i>
        </button>`);
    }
    
    return buttons.join('');
}

/**
 * 渲染参考文档
 */
function renderReferenceDocuments(documents) {
    if (!documents || documents.length === 0) {
        return '<span class="text-muted">无</span>';
    }
    
    return documents.slice(0, 2).map(doc => 
        `<a href="${escapeHtml(doc.url)}" target="_blank" class="doc-link" title="${escapeHtml(doc.title)}">
            <i class="bi bi-file-text"></i>
            ${escapeHtml(doc.title.length > 10 ? doc.title.substring(0, 10) + '...' : doc.title)}
        </a>`
    ).join('') + (documents.length > 2 ? `<span class="text-muted small">+${documents.length - 2}</span>` : '');
}

/**
 * 加载项目选项
 */
function loadProjects() {
    fetch('/api/projects')
        .then(response => response.json())
        .then(projects => {
            allProjects = projects;
            // 填充项目映射表
            projectsMap.clear();
            projects.forEach(project => {
                projectsMap.set(project.id, project.name);
            });
            updateProjectOptions();
        })
        .catch(error => {
            console.error('加载项目列表失败:', error);
        });
}

/**
 * 异步加载项目数据
 */
function loadProjectsAsync() {
    return fetch('/api/projects')
        .then(response => response.json())
        .then(projects => {
            allProjects = projects;
            // 填充项目映射表
            projectsMap.clear();
            projects.forEach(project => {
                projectsMap.set(project.id, project.name);
            });
            updateProjectOptions();
            return projects;
        })
        .catch(error => {
            console.error('加载项目列表失败:', error);
            throw error;
        });
}

/**
 * 更新项目选项
 */
function updateProjectOptions() {
    const selects = ['projectFilter', 'requirementProject'];
    
    selects.forEach(selectId => {
        const select = document.getElementById(selectId);
        if (select) {
            // 保留第一个选项（全部项目/请选择项目）
            const firstOption = select.firstElementChild;
            select.innerHTML = '';
            select.appendChild(firstOption);
            
            allProjects.forEach(project => {
                const option = document.createElement('option');
                option.value = project.id;
                option.textContent = project.name;
                select.appendChild(option);
            });
        }
    });
}

/**
 * 加载开发者列表
 */
function loadDevelopers() {
    fetch('/api/developers')
        .then(response => response.json())
        .then(developers => {
            allDevelopers = developers;
            updateDeveloperOptions();
        })
        .catch(error => {
            console.error('加载开发者列表失败:', error);
        });
}

/**
 * 异步加载开发者数据
 */
function loadDevelopersAsync() {
    return fetch('/api/developers')
        .then(response => response.json())
        .then(developers => {
            allDevelopers = developers;
            updateDeveloperOptions();
            return developers;
        })
        .catch(error => {
            console.error('加载开发者列表失败:', error);
            throw error;
        });
}

/**
 * 更新开发者选项
 */
function updateDeveloperOptions() {
    // 更新创建需求模态框中的负责人选项
    const ownerSelect = document.getElementById('requirementOwner');

    if (ownerSelect) {
        // 保留第一个选项
        const firstOption = ownerSelect.firstElementChild;
        ownerSelect.innerHTML = '';
        ownerSelect.appendChild(firstOption);
        
        allDevelopers.forEach(developer => {
            const option = document.createElement('option');
            option.value = developer.id;
            option.textContent = developer.name;
            ownerSelect.appendChild(option);

        });
    }
}

// 筛选功能已移除

/**
 * 保存需求
 */
function saveRequirement() {
    const form = document.getElementById('addRequirementForm');
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }
    
    const title = document.getElementById('requirementTitle').value.trim();
    const description = document.getElementById('requirementDescription').value.trim();
    const projectId = document.getElementById('requirementProject').value;
    const priority = document.getElementById('requirementPriority').value;
    const ownerId = document.getElementById('requirementOwner').value;
    const deadline = document.getElementById('requirementDeadline').value;
    
    if (!title || !description || !projectId || !priority || !deadline) {
        showErrorToast('请填写所有必填字段');
        return;
    }
    
    const requirementData = {
        title: title,
        description: description,
        priority: priority,
        projectId: parseInt(projectId),
        ownerId: ownerId && ownerId !== '' ? (isNaN(parseInt(ownerId)) ? ownerId : parseInt(ownerId)) : null,
        expectedCompletionDate: deadline,
        referenceDocuments: tempDocuments.map(doc => ({
            title: doc.title,
            url: doc.url
        }))
    };

    fetch('/api/requirements', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(requirementData)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('创建需求失败');
        }
        return response.json();
    })
    .then(data => {
        showSuccessToast('需求创建成功');
        // 清空临时文档数据
        tempDocuments = [];
        documentCounter = 0;
        renderDocumentList();
        bootstrap.Modal.getInstance(document.getElementById('addRequirementModal')).hide();
        loadRequirements();
    })
    .catch(error => {
        console.error('创建需求失败:', error);
        showErrorToast('创建需求失败，请重试');
    });
}

/**
 * 添加参考文档
 */
function addReferenceDocument() {
    const titleElement = document.getElementById('docTitle');
    const urlElement = document.getElementById('docUrl');
    
    if (!titleElement || !urlElement) {
        showErrorToast('无法找到输入框元素');
        return;
    }
    
    const title = titleElement.value.trim();
    const url = urlElement.value.trim();
    
    if (!title || !url) {
        showErrorToast('请填写文档标题和链接');
        return;
    }
    
    const doc = {
        id: ++documentCounter,
        title: title,
        url: url
    };
    
    tempDocuments.push(doc);
    renderDocumentList();
    
    // 清空输入框
    titleElement.value = '';
    urlElement.value = '';
    
    // 显示成功提示
    showSuccessToast('文档已添加');
}

/**
 * 渲染文档列表
 */
function renderDocumentList() {
    const container = document.getElementById('documentList');
    container.innerHTML = '';
    
    if (tempDocuments.length === 0) {
        container.innerHTML = '<div class="text-muted text-center py-2"><i class="bi bi-file-text me-1"></i>暂无参考文档</div>';
        return;
    }
    
    tempDocuments.forEach(doc => {
        const item = document.createElement('div');
        item.className = 'card mb-2';
        item.innerHTML = `
            <div class="card-body p-3">
                <div class="d-flex justify-content-between align-items-start">
                    <div class="flex-grow-1">
                        <h6 class="card-title mb-1">
                            <i class="bi bi-file-text text-primary me-1"></i>
                            ${escapeHtml(doc.title)}
                        </h6>
                        <a href="${escapeHtml(doc.url)}" target="_blank" class="card-link small text-decoration-none">
                            <i class="bi bi-link-45deg me-1"></i>
                            ${escapeHtml(doc.url)}
                        </a>
                    </div>
                    <button type="button" class="btn btn-outline-danger btn-sm ms-2" onclick="removeDocument(${doc.id})" title="删除文档">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            </div>
        `;
        container.appendChild(item);
    });
}

/**
 * 移除文档
 */
function removeDocument(docId) {
    tempDocuments = tempDocuments.filter(doc => doc.id !== docId);
    renderDocumentList();
    showSuccessToast('文档已删除');
}

/**
 * 重置需求表单
 */
function resetRequirementForm() {
    document.getElementById('addRequirementForm').reset();
    document.getElementById('requirementPriority').value = '';
    document.getElementById('requirementOwner').value = '';
    document.getElementById('requirementDeadline').value = '';
    tempDocuments = [];
    documentCounter = 0;
    renderDocumentList();
}

/**
 * 需求操作函数
 */
// 激活功能已移除

// 批准和拒绝功能已移除

function cancelRequirement(id) {
    if (confirm('确定要取消这个需求吗？')) {
        updateRequirementStatus(id, 'cancel', '取消需求');
    }
}

function updateRequirementStatus(id, action, actionName) {
    fetch(`/api/requirements/${id}/${action}`, {
        method: 'POST'
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`${actionName}失败`);
        }
        showSuccessToast(`${actionName}成功`);
        loadRequirements();
    })
    .catch(error => {
        console.error(`${actionName}失败:`, error);
        showErrorToast(`${actionName}失败，请重试`);
    });
}

/**
 * 编辑需求
 */
function editRequirement(id) {
    window.location.href = `/requirements/${id}/edit`;
}

/**
 * 选择相关函数
 */
function toggleSelectAll() {
    const selectAll = document.getElementById('selectAll');
    const checkboxes = document.querySelectorAll('.requirement-checkbox');
    
    checkboxes.forEach(checkbox => {
        checkbox.checked = selectAll.checked;
        toggleRequirementSelection(checkbox);
    });
}

function toggleRequirementSelection(checkbox) {
    const id = checkbox.value;
    if (checkbox.checked) {
        selectedRequirements.add(id);
    } else {
        selectedRequirements.delete(id);
    }
    
    updateSelectAllState();
    updateBulkActions();
}

function updateSelectAllState() {
    const selectAll = document.getElementById('selectAll');
    const checkboxes = document.querySelectorAll('.requirement-checkbox');
    const checkedBoxes = document.querySelectorAll('.requirement-checkbox:checked');
    
    if (checkedBoxes.length === 0) {
        selectAll.indeterminate = false;
        selectAll.checked = false;
    } else if (checkedBoxes.length === checkboxes.length) {
        selectAll.indeterminate = false;
        selectAll.checked = true;
    } else {
        selectAll.indeterminate = true;
        selectAll.checked = false;
    }
}

function updateBulkActions() {
    const bulkActions = document.querySelector('.bulk-actions');
    if (selectedRequirements.size > 0) {
        if (bulkActions) {
            bulkActions.classList.add('show');
            bulkActions.querySelector('.selected-count').textContent = `已选择 ${selectedRequirements.size} 个需求`;
        }
    } else {
        if (bulkActions) {
            bulkActions.classList.remove('show');
        }
    }
}



/**
 * 工具函数
 */
function showLoading() {
    document.getElementById('loadingSpinner').style.display = 'block';
}

function hideLoading() {
    document.getElementById('loadingSpinner').style.display = 'none';
}

function showEmptyState() {
    document.getElementById('emptyState').style.display = 'block';
}

function hideEmptyState() {
    document.getElementById('emptyState').style.display = 'none';
}

function showSuccessToast(message) {
    document.getElementById('successMessage').textContent = message;
    const toast = new bootstrap.Toast(document.getElementById('successToast'));
    toast.show();
}

function showErrorToast(message) {
    document.getElementById('errorMessage').textContent = message;
    const toast = new bootstrap.Toast(document.getElementById('errorToast'));
    toast.show();
}



function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function formatDateTime(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {hour: '2-digit', minute: '2-digit'});
}

function getPriorityText(priority) {
    const priorityMap = {
        'LOW': '低',
        'MEDIUM': '中',
        'HIGH': '高',
        'URGENT': '紧急'
    };
    return priorityMap[priority] || priority;
}

function getStatusText(status) {
    const statusMap = {
        'DRAFT': '草稿',
        'ACTIVE': '激活',
        'APPROVED': '已批准',
        'REJECTED': '已拒绝',
        'CANCELLED': '已取消'
    };
    return statusMap[status] || status;
}

function performGlobalSearch(query) {
    if (query.trim()) {
        currentFilters.search = query.trim();
        currentPage = 0;
        loadRequirements();
    }
}

/**
 * 获取项目显示名称
 */
function getProjectDisplayName(projectId) {
    if (!projectId) {
        return '-';
    }
    const projectName = projectsMap.get(projectId);
    return projectName ? projectName : `项目 ${projectId}`;
}

// 导出功能已移除